﻿/**************************************************************
 *
 * 唯一标识：d87572d1-8a25-4761-aa67-290c9f79619a
 * 命名空间：Sgr.UPMS.Application.Commands.Duties
 * 创建时间：2023/8/27 19:25:17
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：修改职务状态命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.Domain.Entities;
using Sgr.UPMS.Domain.Duties;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Duties
{
    /// <summary>
    /// 修改职务状态命令处理器
    /// </summary>
    public class ModifyDutyStatusCommandHandle : IRequestHandler<ModifyDutyStatusCommand, CommandResult<bool>>
    {
        private readonly IDutyRepository _dutyRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dutyRepository">职务仓储</param>
        public ModifyDutyStatusCommandHandle(IDutyRepository dutyRepository)
        {
            _dutyRepository = dutyRepository;
        }

        /// <summary>
        /// 处理修改职务状态命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(ModifyDutyStatusCommand request, CancellationToken cancellationToken)
        {
            // 查找职务实体
            var duty = await _dutyRepository.GetAsync(request.DutyId, cancellationToken);

            // 如果找不到职务，返回NotFound结果
            if (duty == null)
                return CommandResult.NotFound<bool>("未找到指定的职务");

            // 如果状态未变更，直接返回成功
            if (duty.State == request.State)
                return CommandResult.Success(true, "职务状态未变更");

            // 更新职务状态
            duty.ChangeEntityStates(request.State);

            duty.MarkAsChanged();

            // 更新到仓储
            await _dutyRepository.UpdateAsync(duty, cancellationToken);

            // 返回成功结果
            string statusMessage = request.State == EntityStates.Normal ? "启用" : "停用";
            return CommandResult.Success(true, $"职务{statusMessage}成功");
        }
    }
}